package com.longnuoqi.mydoctor.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.longnuoqi.mydoctor.entity.User;
import com.longnuoqi.mydoctor.utils.ActivityCollection;
import com.longnuoqi.mydoctor.utils.FileUtil;
import com.yunhe.mydoctor.R;


import org.json.JSONException;
import org.json.JSONObject;


import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Lenovo on 2016/1/12.
 */
public class UserProfileActivity extends AppCompatActivity {
    private ImageView back;
    private TextView id;
    private TextView name;
    private TextView gender;
    private TextView birth;
    private TextView city;
    private TextView email;
    private TextView sign;
    private TextView date;
    private RelativeLayout edit;

    private User user;

    private SharedPreferences sharedPreferences;
    private String access_token;
    private String url;
    private static boolean isExit = false;//判断是否退出
    private static boolean hasTask = false;//判断是否是任务
    private Timer timer = new Timer();//声明timer对象，计时器
    private TimerTask timerTask = new TimerTask() {//为timer安排一次执行或重复执行的任务
        @Override
        public void run() {
            isExit = false;
        }
    };

    /*双击退出程序*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!isExit) {
                isExit = true;
                Toast.makeText(UserProfileActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                if (!hasTask) {
                    timer.schedule(timerTask, 2000);//安排在指定延迟后执行指定的任务
                }
            } else {
                ActivityCollection.finishAll();
                //回收资源
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_profile_layout);
        ActivityCollection.addActivity(this);
        init();
        initView();
        getData();
    }

    private void init() {
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        access_token = sharedPreferences.getString("access_token", "");
        url = "http://www.tngou.net/api/user?access_token=" + access_token;
    }

    private void initView() {
        back = (ImageView) findViewById(R.id.user_pro_back_btn);
        edit = (RelativeLayout) findViewById(R.id.user_pro_edit_btn);
        back.setOnClickListener(onClickListener);
        edit.setOnClickListener(onClickListener);

        id = (TextView) findViewById(R.id.user_pro_id_text);
        name = (TextView) findViewById(R.id.user_pro_name_text);
        gender = (TextView) findViewById(R.id.user_pro_gender_text);
        birth = (TextView) findViewById(R.id.user_pro_birth_text);
        city = (TextView) findViewById(R.id.user_pro_home_text);
        email = (TextView) findViewById(R.id.user_pro_mail_text);
        sign = (TextView) findViewById(R.id.user_pro_sign_text);
        date = (TextView) findViewById(R.id.user_pro_date_text);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.user_pro_back_btn:
                    Intent intent = getIntent();
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
                case R.id.user_pro_edit_btn:
                    if (user == null) {
                        Toast.makeText(UserProfileActivity.this, "正在读取个人信息…", Toast.LENGTH_SHORT).show();
                    } else {
                        Intent edit = new Intent(UserProfileActivity.this, UserProfileEditActivity.class);
                        edit.putExtra("user", user);
                        startActivityForResult(edit, 0);
                    }
                    break;
                default:
                    break;
            }

        }
    };

    public void getData() {
        RequestQueue queue = Volley.newRequestQueue(UserProfileActivity.this);
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.e("===================", "s:" + s);
                jsonUser(s);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        queue.add(request);
    }

    private void jsonUser(String s) {
        try {
            JSONObject data = new JSONObject(s);
            user = new User();
            user.setId(data.getInt("id"));
            user.setAccount(data.getString("account"));
            user.setGender(data.getInt("gender"));
            user.setEmail(data.getString("email"));
            user.setTime(data.getLong("time"));
            user.setBirth(data.getLong("birth"));
            user.setCity(data.getString("city"));
            user.setSignature(data.getString("signature"));

            Log.e("===================", "getGender:" + user.getGender());
            if (user.getGender() == 1) {
                gender.setText("男");
            } else if (user.getGender() == 0) {
                gender.setText("女");
            } else {
                gender.setText("保密");
            }
            Log.e("===================", "id:" + user.getId());
            id.setText(user.getId() + "");
            Log.e("===================", "name:" + user.getAccount());
            name.setText(user.getAccount());
            Log.e("===================", "email:" + user.getEmail());
            email.setText(user.getEmail());
            Log.e("===================", "date:" + user.getTime());
            date.setText(FileUtil.dateFormat(user.getTime()));
            Log.e("===================", "birth:" + user.getBirth());
            birth.setText(FileUtil.dateFormat(user.getBirth()));
            Log.e("===================", "city:" + user.getCity());
            city.setText(user.getCity());
            Log.e("===================", "sign:" + user.getSignature());
            sign.setText(user.getSignature());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 2:
                getData();
                break;
            default:
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollection.removeActivity(this);
    }
}
